package com.moyou.weichat.fragment;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMConversation;
import com.moyou.weichat.R;
import com.moyou.weichat.bean.MessageNotificationBean;
import com.moyou.weichat.chat.ChatManger;
import com.moyou.weichat.chat.ChatVerticalListAdater;
import com.moyou.weichat.listener.ChatConnctionUIHandler;
import com.moyou.weichat.listener.ChatEMConnectionListener;
import com.moyou.weichat.listener.ChatMessageDeleteListener;
import com.moyou.weichat.mvp.presenter.ChatVerticalPresenter;
import com.moyou.weichat.mvp.view.ChatVerticalView;
import com.moyou.weichat.utils.ChatUtils;
import com.moyou.weichat.utils.ConstantUtils;
import com.moyou.weichat.utils.RecyclerViewHoper;
import com.victor.loading.rotate.RotateLoading;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;

/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * Use the {@link ChatFragment#newInstance} factory method to
 * create an instance of this fragment.
 * sj: 2017年10月17日10:45:23
 * name: ts
 * 用途：聊天页面
 */
public class ChatFragment extends BaseFragment implements ChatVerticalView , ChatMessageDeleteListener {
    @Bind(R.id.chat_RecyclerView)
    RecyclerView mChatRecyclerView;
    @Bind(R.id.title_name)
    TextView titleName;
    @Bind(R.id.chatLinkState)
    RelativeLayout chatLinkState;
    @Bind(R.id.rotateloading)
    RotateLoading rotateLoading;

    private ChatVerticalListAdater chatVerticalListAdater; //聊天的适配器
    private List<EMConversation> chatVeryocalList;  //聊天的数据元
    private ChatVerticalPresenter chatVerticalPresenter; //聊天列表的控制器
    private int chatPosition;
    private ChatConnctionUIHandler chatConnctionUIHandler;

    public static ChatFragment newInstance() {
        ChatFragment fragment = new ChatFragment();
        Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    protected void initData(Bundle arguments) {
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
    }

    @Override
    protected void initView() {
        titleName.setText("微聊");
        chatVeryocalList = new ArrayList<>();
        chatVerticalPresenter = new ChatVerticalPresenter(this);
        chatConnctionUIHandler = new ChatConnctionUIHandler(chatLinkState,rotateLoading);
        chatVerticalListAdater = new ChatVerticalListAdater(R.layout.chat_vertical_item, chatVeryocalList);
        RecyclerViewHoper.getSingleHoper().initRecyclerViewV(mActivity, mChatRecyclerView, chatVerticalListAdater);
        chatVerticalListAdater.addHeaderView(chatVerticalPresenter.initHeaderView(mActivity, R.layout.chat_vertical_item));
        mChatRecyclerView.addOnItemTouchListener(new OnItemClickListener() {
            @Override
            public void onSimpleItemClick(BaseQuickAdapter adapter, View view, int position) {
                chatPosition = position;
                //跳转聊天页面
                ChatUtils.getChatUtils(mActivity).startChatActivity(chatVeryocalList.get(position).conversationId() ,
                        chatVeryocalList.get(position).getType());
            }
        });
    }

    @Override
    protected void setListener() {
        chatVerticalListAdater.setChatMessageDeleteListener(this);
        //监听环信的链接异常
        EMClient.getInstance().addConnectionListener(new ChatEMConnectionListener(chatConnctionUIHandler));
    }

    @Override
    protected int setLayoutResouceId() {
        return R.layout.fragment_chat;
    }

    //这里是通知聊天的其中的模条会话进行刷新！
    @Subscribe
    public void notificationMessageList( MessageNotificationBean messageNotificationBean ) {
        if (messageNotificationBean.getMessageType() == ConstantUtils.CHAT_NOTIFICATION_NUMBER ||
                messageNotificationBean.getMessageType() == ConstantUtils.CHAT_NOTIFICATION_REFSH) {
            mActivity.runOnUiThread(() -> refresh());
        }
    }
    //刷新
    public void refresh(){
        chatVeryocalList.clear();
        chatVeryocalList.addAll(ChatManger.getChatManger().getChatConversationList(mActivity));
        if(chatVerticalListAdater != null){
            chatVerticalListAdater.notifyDataSetChanged();
        }
    }

    //删除该会话
    @Override
    public void onDeleteMessage( String userName , int position ) {
        ChatUtils.getChatUtils(mActivity).deleteMessage( userName , position , chatVerticalListAdater , chatVeryocalList );
    }

    @Override
    public void onResume() {
        super.onResume();
        //加载数据
        ChatManger.getChatManger().loadChatDate();
        refresh();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        rotateLoading.stop();
    }
}
